package com.hzy.common.ai;

import cn.hutool.json.JSONUtil; // 1. 引入Hutool的JSON工具
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class AIModelInvoker {

    @Autowired
    private BaiduAIProperties baiduAIProperties;

    private static final OkHttpClient HTTP_CLIENT = new OkHttpClient.Builder()
            .readTimeout(300, TimeUnit.SECONDS)
            .build();

    /**
     * 向百度千帆大模型发送一个消息。
     *
     * @param content 要发送给AI的内容
     * @return AI模型的响应结果字符串
     * @throws IOException 当网络请求失败时抛出
     */
    public String qianfanInvoker(String content) throws IOException {

        String apiUrl = baiduAIProperties.getApiUrl();
        String apiModel = baiduAIProperties.getQianfanModel();
        String authorizationHeader = baiduAIProperties.getAuthorizationHeader();

        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");

        // ======================= 关键修改点：开始 =======================
        // 2. 使用Map来构建请求体结构，而不是手动拼接字符串
        Map<String, Object> message = new HashMap<>();
        message.put("role", "user");
        message.put("content", content); // 将包含特殊字符的prompt安全地放入Map

        Map<String, Object> webSearchOptions = new HashMap<>();
        webSearchOptions.put("enable", false);
        webSearchOptions.put("enable_citation", false);
        webSearchOptions.put("enable_trace", false);

        Map<String, Object> payload = new HashMap<>();
        payload.put("model", apiModel);
        payload.put("messages", Collections.singletonList(message)); // messages 是一个列表
        payload.put("web_search", webSearchOptions);

        // 3. 使用Hutool将Map对象序列化为正确的JSON字符串，它会自动处理所有转义
        String requestJson = JSONUtil.toJsonStr(payload);
        // ======================= 关键修改点：结束 =======================

        RequestBody body = RequestBody.create(mediaType, requestJson);

        Request request = new Request.Builder()
                .url(apiUrl)
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                // .addHeader("appid", "") // 这个header通常不需要，可以尝试移除
                .addHeader("Authorization", authorizationHeader)
                .build();

        try (Response response = HTTP_CLIENT.newCall(request).execute()) {
            if (!response.isSuccessful() || response.body() == null) {
                // 打印出失败时的响应体，这对于调试非常有用
                String errorBody = response.body() != null ? response.body().string() : "null";
                throw new IOException("调用百度千帆API失败: " + response + ", 响应体: " + errorBody);
            }
            return response.body().string();
        }
    }
}